#include "game.h"
#include <iostream>
#include <algorithm>
#include <ctime>

// 构造函数（初始化窗口、蛇、食物、字体）
Game::Game() : 
    window(sf::VideoMode(WIDTH* BLOCK_SIZE, HEIGHT* BLOCK_SIZE + PANEL_HEIGHT), "SFML Snake"),
    playerSnake(WIDTH / 2, HEIGHT / 4, RIGHT, SNAKE_COLOR, SNAKE_BORDER_COLOR),
    aiSnake1(WIDTH / 4, HEIGHT / 2, RIGHT, AISNAKE_COLOR, AISNAKE_BORDER_COLOR),
    aiSnake2(3 * WIDTH / 4, HEIGHT / 2, LEFT, ROBOTSNAKE_COLOR, ROBOTSNAKE_BORDER_COLOR),
    rng(std::mt19937(static_cast<unsigned int>(std::time(nullptr))))
{
    // 加载系统字体（多路径 fallback，适配不同Windows环境）
    std::vector<std::string> fontPaths = {
        "C:\\Windows\\Fonts\\simhei.ttf",
        "C:\\Windows\\Fonts\\msyh.ttc",
        "C:\\Windows\\Fonts\\arial.ttf",
        "C:\\Windows\\Fonts\\times.ttf",
        "C:\\Windows\\Fonts\\simsun.ttc"
    };
    bool fontLoaded = false;
    for (const auto& path : fontPaths) {
        if (font.loadFromFile(path)) {
            // 修复：中文输出用ASCII兼容格式，避免编码截断
            std::cout << "Cheng Gong Jia Zai Zi Ti: " << path << std::endl;
            fontLoaded = true;
            break;
        }
    }
    if (!fontLoaded) {
        // 修复：中文输出用ASCII兼容格式，避免编码截断
        std::cerr << "Jing Gao: Zi Ti Jia Zai Shi Bai, Wu Fa Xian Shi Wen Ben!" << std::endl;
    }

    // 生成初始食物
    std::vector<Snake> snakes = { playerSnake, aiSnake1, aiSnake2 };
    food.generate(snakes);
    // 修复：中文输出用ASCII兼容格式，避免编码截断
    Point foodPos = food.getPosition();
    std::cout << "Chu Shi Shi Wu Wei Zhi: (" << foodPos.x << ", " << foodPos.y << ")" << std::endl;

    // 初始化按钮
    initButtons();
}

// AI1方向决策（追逐食物）
Direction Game::getAIDirection(const Snake& aiSnake, Direction currentDir, int& dirFrames) {
    Point head = aiSnake.getHead();
    Point foodPos = food.getPosition();
    int dx = foodPos.x - head.x;
    int dy = foodPos.y - head.y;

    // 计算当前方向的下一个位置
    Point currentDirPos = head;
    switch (currentDir) {
    case LEFT:  currentDirPos.x--; break;
    case RIGHT: currentDirPos.x++; break;
    case UP:    currentDirPos.y--; break;
    case DOWN:  currentDirPos.y++; break;
    default: return RIGHT;
    }

    // 确保方向至少保持MIN_DIR_FRAMES帧，避免频繁转向
    if (dirFrames < MIN_DIR_FRAMES) {
        if (isSafe(currentDirPos, aiSnake)) {
            dirFrames++;
            return currentDir;
        }
        else {
            dirFrames = 0;
        }
    }
    else {
        dirFrames = 0;
    }

    // 检查当前方向是否朝向食物
    bool isTowardFood = false;
    switch (currentDir) {
    case LEFT:  isTowardFood = (dx < 0); break;
    case RIGHT: isTowardFood = (dx > 0); break;
    case UP:    isTowardFood = (dy < 0); break;
    case DOWN:  isTowardFood = (dy > 0); break;
    }
    if (isSafe(currentDirPos, aiSnake) && isTowardFood) {
        dirFrames++;
        return currentDir;
    }

    // 优先沿X轴（水平）向食物移动
    if (abs(dx) >= abs(dy)) {
        if (dx > 0 && currentDir != LEFT) {
            Point nextPos(head.x + 1, head.y);
            if (isSafe(nextPos, aiSnake)) return RIGHT;
        }
        if (dx < 0 && currentDir != RIGHT) {
            Point nextPos(head.x - 1, head.y);
            if (isSafe(nextPos, aiSnake)) return LEFT;
        }
        if (dy > 0 && currentDir != UP) {
            Point nextPos(head.x, head.y + 1);
            if (isSafe(nextPos, aiSnake)) return DOWN;
        }
        if (dy < 0 && currentDir != DOWN) {
            Point nextPos(head.x, head.y - 1);
            if (isSafe(nextPos, aiSnake)) return UP;
        }
    }
    // 优先沿Y轴（垂直）向食物移动
    else {
        if (dy > 0 && currentDir != UP) {
            Point nextPos(head.x, head.y + 1);
            if (isSafe(nextPos, aiSnake)) return DOWN;
        }
        if (dy < 0 && currentDir != DOWN) {
            Point nextPos(head.x, head.y - 1);
            if (isSafe(nextPos, aiSnake)) return UP;
        }
        if (dx > 0 && currentDir != LEFT) {
            Point nextPos(head.x + 1, head.y);
            if (isSafe(nextPos, aiSnake)) return RIGHT;
        }
        if (dx < 0 && currentDir != RIGHT) {
            Point nextPos(head.x - 1, head.y);
            if (isSafe(nextPos, aiSnake)) return LEFT;
        }
    }

    // 若无最优路径，随机选择一个安全方向
    std::vector<Direction> possibleDirs = { LEFT, RIGHT, UP, DOWN };
    std::shuffle(possibleDirs.begin(), possibleDirs.end(), rng);
    for (auto d : possibleDirs) {
        if ((d == LEFT && currentDir != RIGHT) || (d == RIGHT && currentDir != LEFT) ||
            (d == UP && currentDir != DOWN) || (d == DOWN && currentDir != UP)) {
            Point nextPos = head;
            switch (d) {
            case LEFT: nextPos.x--; break;
            case RIGHT: nextPos.x++; break;
            case UP: nextPos.y--; break;
            case DOWN: nextPos.y++; break;
            default: break;
            }
            if (isSafe(nextPos, aiSnake)) return d;
        }
    }
    return currentDir;
}

// AI2方向决策（优先躲避玩家，再追逐食物）
Direction Game::getAI2Direction() {
    Point head = aiSnake2.getHead();
    Point playerHead = playerSnake.getHead();
    int dxPlayer = playerHead.x - head.x;
    int dyPlayer = playerHead.y - head.y;

    // 若距离玩家小于等于3格，优先躲避
    if (abs(dxPlayer) + abs(dyPlayer) <= 3) {
        if (dxPlayer > 0 && aiSnake2.getDirection() != RIGHT) {
            Point nextPos(head.x - 1, head.y);
            if (isSafe(nextPos, aiSnake2)) {
                ai2DirFrames = 0;
                return LEFT;
            }
        }
        if (dxPlayer < 0 && aiSnake2.getDirection() != LEFT) {
            Point nextPos(head.x + 1, head.y);
            if (isSafe(nextPos, aiSnake2)) {
                ai2DirFrames = 0;
                return RIGHT;
            }
        }
        if (dyPlayer > 0 && aiSnake2.getDirection() != DOWN) {
            Point nextPos(head.x, head.y - 1);
            if (isSafe(nextPos, aiSnake2)) {
                ai2DirFrames = 0;
                return UP;
            }
        }
        if (dyPlayer < 0 && aiSnake2.getDirection() != UP) {
            Point nextPos(head.x, head.y + 1);
            if (isSafe(nextPos, aiSnake2)) {
                ai2DirFrames = 0;
                return DOWN;
            }
        }
    }

    // 玩家安全时，按AI1逻辑追逐食物
    return getAIDirection(aiSnake2, aiSnake2.getDirection(), ai2DirFrames);
}

// 检查位置是否安全（无边界碰撞、无自身碰撞、无其他蛇碰撞）
bool Game::isSafe(const Point& pos, const Snake& selfSnake) {
    // 边界碰撞
    if (pos.x < 0 || pos.x >= WIDTH || pos.y < 0 || pos.y >= HEIGHT)
        return false;

    // 自身碰撞
    if (selfSnake.checkSelfCollision(pos))
        return false;

    // 其他蛇碰撞
    if (playerSnake.checkCollision(pos) && playerSnake.getHead() != pos)
        return false;
    if (aiSnake1.checkCollision(pos) && aiSnake1.getHead() != pos)
        return false;
    if (aiSnake2.checkCollision(pos) && aiSnake2.getHead() != pos)
        return false;
        
    return true;
}

// 初始化按钮
void Game::initButtons() {
    // 单人模式按钮
    singlePlayerButton.setSize(sf::Vector2f(200, 50));
    singlePlayerButton.setPosition(WIDTH * BLOCK_SIZE / 2 - 100, HEIGHT * BLOCK_SIZE / 2 - 20 + PANEL_HEIGHT);
    singlePlayerButton.setFillColor(sf::Color(50, 50, 50)); // 默认深灰色
    singlePlayerButton.setOutlineColor(sf::Color::White);
    singlePlayerButton.setOutlineThickness(2);
    //局域网模式按钮
    onlineModeButton.setSize(sf::Vector2f(200, 50)); 
    onlineModeButton.setPosition(
        WIDTH * BLOCK_SIZE / 2 - 100,
        HEIGHT * BLOCK_SIZE / 2 - 20 + PANEL_HEIGHT + 50 + 20
    );
    onlineModeButton.setFillColor(sf::Color(50, 50, 50)); 
    onlineModeButton.setOutlineColor(sf::Color::White);
    onlineModeButton.setOutlineThickness(2);
    // 按钮文本（字体加载成功时）
    if (font.getInfo().family != "") {
        singlePlayerText.setFont(font);
        singlePlayerText.setString("SINGLE PLAYER");
        singlePlayerText.setCharacterSize(24);
        singlePlayerText.setFillColor(sf::Color::White);
        sf::FloatRect textRect = singlePlayerText.getLocalBounds();
        singlePlayerText.setOrigin(textRect.width / 2, textRect.height / 2);
        singlePlayerText.setPosition(WIDTH * BLOCK_SIZE / 2, HEIGHT * BLOCK_SIZE / 2 + PANEL_HEIGHT);
        onlineModeText.setFont(font);
        onlineModeText.setString("ONLINE MODE"); 
        onlineModeText.setCharacterSize(24);
        onlineModeText.setFillColor(sf::Color::White);
        sf::FloatRect onlineTextRect = onlineModeText.getLocalBounds();
        onlineModeText.setOrigin(onlineTextRect.width / 2, onlineTextRect.height / 2);
        onlineModeText.setPosition(
            WIDTH * BLOCK_SIZE / 2,
            HEIGHT * BLOCK_SIZE / 2 - 20 + PANEL_HEIGHT + 50 + 20 + 25
        );
    }
}

// 处理输入（键盘+鼠标）
void Game::handleInput() {
    sf::Event event;
    while (window.pollEvent(event)) {
        // 关闭窗口
        if (event.type == sf::Event::Closed) {
            window.close();
            gameOver = true;
            return;
        }

        // 键盘输入（游戏中）
        if (event.type == sf::Event::KeyPressed) {
            if (gameStarted) {
                switch (event.key.code) {
                case sf::Keyboard::A: 
                    if (playerSnake.getDirection() != RIGHT) 
                        playerSnake.setNextDirection(LEFT); 
                    break;
                case sf::Keyboard::D: 
                    if (playerSnake.getDirection() != LEFT) 
                        playerSnake.setNextDirection(RIGHT); 
                    break;
                case sf::Keyboard::W: 
                    if (playerSnake.getDirection() != DOWN) 
                        playerSnake.setNextDirection(UP); 
                    break;
                case sf::Keyboard::S: 
                    if (playerSnake.getDirection() != UP) 
                        playerSnake.setNextDirection(DOWN); 
                    break;
                case sf::Keyboard::X: gameOver = true; break;
                }
            }
        }

        // 鼠标移动事件 - 处理按钮悬停
        else if (event.type == sf::Event::MouseMoved) {
            if (!gameStarted) {
                sf::Vector2i mousePos = sf::Mouse::getPosition(window);
                if (singlePlayerButton.getGlobalBounds().contains(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y))) {
                    singlePlayerButtonHovered = true;
                    singlePlayerButton.setFillColor(sf::Color(80, 80, 80)); // 悬停时浅灰色
                }
                else {
                    singlePlayerButtonHovered = false;
                    singlePlayerButton.setFillColor(sf::Color(50, 50, 50)); // 默认深灰色
                }
                if (onlineModeButton.getGlobalBounds().contains(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y))) {
                    onlineModeButtonHovered = true;
                    onlineModeButton.setFillColor(sf::Color(80, 80, 80)); // 悬停浅灰色
                }
                else {
                    onlineModeButtonHovered = false;
                    onlineModeButton.setFillColor(sf::Color(50, 50, 50)); // 默认深灰色
                }
            }         
        }

        // 鼠标点击事件 - 处理按钮点击
        else if (event.type == sf::Event::MouseButtonPressed) {
            if (!gameStarted && event.mouseButton.button == sf::Mouse::Left) {
                sf::Vector2i mousePos = sf::Mouse::getPosition(window);
                if (singlePlayerButton.getGlobalBounds().contains(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y))) {
                    gameStarted = true;
                    playerSnake.setDirection(RIGHT);
                    playerSnake.setNextDirection(RIGHT);
                }
            }
        }
    }
}

// 更新游戏状态（蛇移动、碰撞检测、分数更新）
void Game::update() {
    if (!gameStarted) return;

    // 更新玩家蛇
    Point playerHead = playerSnake.getHead();
    Point newPlayerHead = playerHead;
    Direction playerDir = playerSnake.getNextDirection();
    
    switch (playerDir) {
    case LEFT:  newPlayerHead.x--; break;
    case RIGHT: newPlayerHead.x++; break;
    case UP:    newPlayerHead.y--; break;
    case DOWN:  newPlayerHead.y++; break;
    default: break;
    }
    
    // 屏幕环绕（从一侧穿出，从另一侧进入）
    if (newPlayerHead.x < 0) newPlayerHead.x = WIDTH - 1;
    else if (newPlayerHead.x >= WIDTH) newPlayerHead.x = 0;
    if (newPlayerHead.y < 0) newPlayerHead.y = HEIGHT - 1;
    else if (newPlayerHead.y >= HEIGHT) newPlayerHead.y = 0;

    // 碰撞检测（游戏结束）
    if (!isSafe(newPlayerHead, playerSnake)) {
        gameOver = true;
        return;
    }

    // 检查是否吃到食物
    bool playerEatFood = (newPlayerHead == food.getPosition());
    playerSnake.move(food.getPosition(), playerEatFood);
    
    // 吃到食物（蛇变长，加分）
    if (playerEatFood) {
        playerScore += 10;
        // 修复：中文输出用ASCII兼容格式，避免编码截断
        std::cout << "Wan Jia Chi Dao Shi Wu! Fen Shu: " << playerScore << std::endl;
        
        // 重新生成食物
        std::vector<Snake> snakes = { playerSnake, aiSnake1, aiSnake2 };
        food.generate(snakes);
    }

    // 更新AI1蛇
    Direction nextDir2 = getAIDirection(aiSnake1, aiSnake1.getDirection(), ai1DirFrames);
    aiSnake1.setNextDirection(nextDir2);
    
    Point head2 = aiSnake1.getHead();
    Point newHead2 = head2;
    switch (nextDir2) {
    case LEFT:  newHead2.x--; break;
    case RIGHT: newHead2.x++; break;
    case UP:    newHead2.y--; break;
    case DOWN:  newHead2.y++; break;
    default: break;
    }
    
    // 屏幕环绕
    if (newHead2.x < 0) newHead2.x = WIDTH - 1;
    else if (newHead2.x >= WIDTH) newHead2.x = 0;
    if (newHead2.y < 0) newHead2.y = HEIGHT - 1;
    else if (newHead2.y >= HEIGHT) newHead2.y = 0;

    // 碰撞检测（游戏结束）
    if (!isSafe(newHead2, aiSnake1)) {
        gameOver = true;
        return;
    }

    // 移动AI1蛇
    bool ai1EatFood = (newHead2 == food.getPosition());
    aiSnake1.move(food.getPosition(), ai1EatFood);
    
    if (ai1EatFood) {
        ai1Score += 5;
        // 中文输出用ASCII兼容格式，避免编码截断
        std::cout << "AI1 Chi Dao Shi Wu! Fen Shu: " << ai1Score << std::endl;
        
        // 重新生成食物
        std::vector<Snake> snakes = { playerSnake, aiSnake1, aiSnake2 };
        food.generate(snakes);
    }

    // 更新AI2蛇
    Direction nextDir3 = getAI2Direction();
    aiSnake2.setNextDirection(nextDir3);
    
    Point head3 = aiSnake2.getHead();
    Point newHead3 = head3;
    switch (nextDir3) {
    case LEFT:  newHead3.x--; break;
    case RIGHT: newHead3.x++; break;
    case UP:    newHead3.y--; break;
    case DOWN:  newHead3.y++; break;
    default: break;
    }
    
    // 屏幕环绕
    if (newHead3.x < 0) newHead3.x = WIDTH - 1;
    else if (newHead3.x >= WIDTH) newHead3.x = 0;
    if (newHead3.y < 0) newHead3.y = HEIGHT - 1;
    else if (newHead3.y >= HEIGHT) newHead3.y = 0;

    // 碰撞检测（游戏结束）
    if (!isSafe(newHead3, aiSnake2)) {
        gameOver = true;
        return;
    }

    // 移动AI2蛇
    bool ai2EatFood = (newHead3 == food.getPosition());
    aiSnake2.move(food.getPosition(), ai2EatFood);
    
    if (ai2EatFood) {
        ai2Score += 5;
        // 中文输出用ASCII兼容格式，避免编码截断
        std::cout << "AI2 Chi Dao Shi Wu! Fen Shu: " << ai2Score << std::endl;
        
        // 重新生成食物
        std::vector<Snake> snakes = { playerSnake, aiSnake1, aiSnake2 };
        food.generate(snakes);
    }
}

// 绘制游戏元素（蛇、食物、UI界面）
void Game::draw() {
    window.clear(sf::Color::Black);

    // 绘制顶部信息面板
    sf::RectangleShape topPanel(sf::Vector2f(WIDTH * BLOCK_SIZE, PANEL_HEIGHT));
    topPanel.setFillColor(sf::Color(20, 20, 20));
    window.draw(topPanel);

    // 绘制游戏边界
    sf::RectangleShape border(sf::Vector2f(WIDTH * BLOCK_SIZE, HEIGHT * BLOCK_SIZE));
    border.setOutlineColor(BORDER_COLOR);
    border.setOutlineThickness(1);
    border.setFillColor(sf::Color::Transparent);
    border.setPosition(0, PANEL_HEIGHT);
    window.draw(border);

    // 绘制所有蛇
    playerSnake.draw(window);
    aiSnake1.draw(window);
    aiSnake2.draw(window);

    // 绘制食物
    food.draw(window);

    // 绘制文本
    if (font.getInfo().family != "") {
        // 菜单界面
        if (!gameStarted) {
            // 绘制单人模式按钮
            window.draw(singlePlayerButton);
            window.draw(singlePlayerText);

            // 绘制蛇颜色说明
            sf::Text infoText("Green: Player | Blue: AI1 | Purple: AI2", font, 16);
            infoText.setFillColor(sf::Color::White);
            sf::FloatRect textRect = infoText.getLocalBounds();
            infoText.setOrigin(textRect.width / 2, textRect.height / 2);
            infoText.setPosition(WIDTH * BLOCK_SIZE / 2, HEIGHT * BLOCK_SIZE + PANEL_HEIGHT - 40);
            window.draw(infoText);
        }
        // 游戏中界面
        else {
            // 玩家分数
            sf::Text playerText("Player: " + std::to_string(playerScore), font, 20);
            playerText.setFillColor(sf::Color::Yellow);
            playerText.setPosition(20, 15);
            window.draw(playerText);

            // AI1分数
            sf::Text ai1Text("AI1: " + std::to_string(ai1Score), font, 18);
            ai1Text.setFillColor(AISNAKE_COLOR);
            ai1Text.setPosition(WIDTH * BLOCK_SIZE - ai1Text.getLocalBounds().width - 20, 10);
            window.draw(ai1Text);

            // AI2分数
            sf::Text ai2Text("AI2: " + std::to_string(ai2Score), font, 18);
            ai2Text.setFillColor(ROBOTSNAKE_COLOR);
            ai2Text.setPosition(WIDTH * BLOCK_SIZE - ai2Text.getLocalBounds().width - 20, 30);
            window.draw(ai2Text);

            // 控制提示
            sf::Text controlText("W/A/S/D: Move | X: Quit ", font, 16);
            controlText.setFillColor(sf::Color::White);
            controlText.setPosition(10, HEIGHT * BLOCK_SIZE + PANEL_HEIGHT - 30);
            window.draw(controlText);
        }
    }
    window.display();
}

// 游戏主循环
void Game::run() {
    while (window.isOpen() && !gameOver) {
        handleInput();
        if (!gameOver) {
            update();
            draw();
        }
        sf::sleep(sf::milliseconds(gameSpeed));
    }

    // 游戏结束界面
    window.clear(sf::Color::Black);
    if (font.getInfo().family != "") {
        sf::Text gameOverText("Game Over!", font, 30);
        gameOverText.setFillColor(sf::Color::Red);
        gameOverText.setPosition(WIDTH * BLOCK_SIZE / 2 - 60, HEIGHT * BLOCK_SIZE / 2 - 60 + PANEL_HEIGHT);
        window.draw(gameOverText);

        sf::Text scoreText("Final Scores:", font, 22);
        scoreText.setFillColor(sf::Color::White);
        scoreText.setPosition(WIDTH * BLOCK_SIZE / 2 - 70, HEIGHT * BLOCK_SIZE / 2 - 20 + PANEL_HEIGHT);
        window.draw(scoreText);

        sf::Text playerFinal("Player: " + std::to_string(playerScore), font, 20);
        playerFinal.setFillColor(sf::Color::Yellow);
        playerFinal.setPosition(WIDTH * BLOCK_SIZE / 2 - 50, HEIGHT * BLOCK_SIZE / 2 + 10 + PANEL_HEIGHT);
        window.draw(playerFinal);

        sf::Text ai1Final("AI1: " + std::to_string(ai1Score), font, 20);
        ai1Final.setFillColor(AISNAKE_COLOR);
        ai1Final.setPosition(WIDTH * BLOCK_SIZE / 2 - 50, HEIGHT * BLOCK_SIZE / 2 + 40 + PANEL_HEIGHT);
        window.draw(ai1Final);

        sf::Text ai2Final("AI2: " + std::to_string(ai2Score), font, 20);
        ai2Final.setFillColor(ROBOTSNAKE_COLOR);
        ai2Final.setPosition(WIDTH * BLOCK_SIZE / 2 - 50, HEIGHT * BLOCK_SIZE / 2 + 70 + PANEL_HEIGHT);
        window.draw(ai2Final);

        sf::Text exitText("Press any key to exit", font, 18);
        exitText.setFillColor(sf::Color::White);
        exitText.setPosition(WIDTH * BLOCK_SIZE / 2 - 80, HEIGHT * BLOCK_SIZE / 2 + 110 + PANEL_HEIGHT);
        window.draw(exitText);
    }
    window.display();

    // 等待输入后关闭窗口
    sf::Event event;
    while (window.waitEvent(event)) {
        if (event.type == sf::Event::KeyPressed || event.type == sf::Event::MouseButtonPressed) {
            window.close();
            break;
        }
    }
}